package com.asg.controller;

import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.asg.entity.ClassTable;
import com.asg.entity.Student;
import com.asg.service.ClassTableService;
import com.asg.service.StudentService;

@Controller
public class StudentController {
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private ClassTableService classTableService;
	
	@RequestMapping("/studentPage")
	public String student(Model model) {
	    List<ClassTable> classList = classTableService.getAll();
	    model.addAttribute("classList", classList);
		return "student";
	}
	
	
	@RequestMapping("/addStu")
	@ResponseBody
	public Object addStudent(Student student) {
		
		HashMap<String, Object> result = new HashMap<>();
		int num = studentService.addStudent(student);
		if(num>0) {
			result.put("code", 0);
			result.put("msg","添加成功");
		}else {
			result.put("code", 1);
			result.put("msg","添加失败");
		}
		result.put("num",num);
		return result;
	}
	
	@RequestMapping("/editStu")
	@ResponseBody
	public Object updateStudent(Student student) {
		HashMap<String, Object> result = new HashMap<>();
		int num = studentService.updateStudent(student);
		if(num>0) {
			result.put("code", 0);
			result.put("msg","编辑成功");
		}else {
			result.put("code", 1);
			result.put("msg","编辑失败");
		}
		result.put("num",num);
		return result;
	}
	
	@RequestMapping("/delStu")
	@ResponseBody
	public Object delStudent(Integer studentId) {
		HashMap<String, Object> result = new HashMap<>();
		int num = studentService.delStudent(studentId);
		if(num>0) {
			result.put("code", 0);
			result.put("msg","删除成功");
		}else {
			result.put("code", 1);
			result.put("msg","删除失败");
		}
		result.put("num",num);
		return result;
	}
	
	@RequestMapping("/getList")
	@ResponseBody
	public Object getList(Integer page, Integer limit, String studentName, Integer classId,String gender) {
		HashMap<String, Object> result = new HashMap<>();
		List<Student> data = studentService.getList(page, limit, studentName, classId,gender);
		int count = studentService.getCount(studentName, classId,gender);
		result.put("code", 0);
		result.put("msg","成功");
		result.put("data", data);
		result.put("count",count);
		return result;
		
	}
	
	@RequestMapping("formPage")
	public String form(Integer studentId,Model model) {
		if(studentId!=null) {
			Student stu = studentService.getStudentById(studentId);
			model.addAttribute("stu",stu);
		}
		List<ClassTable> cls = classTableService.getAll();
		model.addAttribute("cls",cls);
		return "form";
	}
}
